package com.quickcancellation.crm.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quickcancellation.crm.config.LogAspect;
import com.quickcancellation.crm.pojo.dto.PageDto;
import com.quickcancellation.crm.pojo.dto.PageParamsDto;
import com.quickcancellation.crm.pojo.dto.ResponseDto;
import com.quickcancellation.crm.pojo.entity.*;
import com.quickcancellation.crm.service.*;
import com.quickcancellation.crm.utils.DateUtils;
import com.quickcancellation.crm.utils.JSONUtils;
import com.quickcancellation.crm.utils.PageUtils;
import com.quickcancellation.crm.utils.ResponseUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2023-03-12
 */

@RequestMapping("/order")
@CrossOrigin
@RestController
@Api(tags = "订单")
@SaCheckLogin
@SaCheckRole("order")
public class OrderController {

    private final static Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Resource
    private IOrderService orderService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private IUserinfoService userinfoService;

    @Resource
    private IOrderdetailService orderDetailService;
    @Resource
    private IOrderstatuslogService orderStatusLogService;

    @Resource
    private IActivityService activityService;

    @Resource
    private IProductitemService productitemService;

    @Resource
    private IProductService productService;

    @Resource
    private IStoreService storeService;

    @Resource
    private IDistributorService distributorService;

    @PostMapping("list")
    @LogAspect()
    @ApiOperation("列表查询")
    public ResponseDto list(@RequestBody PageParamsDto<Map> params) {

        PageDto<Map> pageDto = PageUtils.getPageParams(params);

        List<Map> list = orderService.getOrderList(pageDto);

        Long count = orderService.getOrderListCount(pageDto);




        return ResponseUtil.success(count,list);
    }

    @PostMapping("detailList")
    @LogAspect()
    @ApiOperation("列表查询")
    public ResponseDto detailList(@RequestBody Map params) {

        String orderCode = MapUtils.getString(params, "orderCode");

        List<Map> orderDetailList = orderDetailService.getOrderDetailList(orderCode);

        return ResponseUtil.success(orderDetailList);
    }

    @PostMapping("auditList")
    @LogAspect()
    @ApiOperation("审核列表")
    public ResponseDto auditList(@RequestBody Map params) {

        String orderCode = MapUtils.getString(params, "orderCode");

        List<Map> orderAuditList = orderStatusLogService.getOrderAuditList(orderCode);

        return ResponseUtil.success(orderAuditList);
    }

    @PostMapping("save")
    @LogAspect()
    @ApiOperation("保存订单")
    public ResponseDto list(@RequestBody Map<String,Object> params) {
        Object orderObj = MapUtils.getObject(params, "order");
        Object orderDetailListStr = MapUtils.getObject(params, "orderDetailList");

        // 获取订单主信息
        Order order = JSONUtils.getEntity(orderObj, Order.class);

//        JSONArray jsonArray = JSONObject.parseArray(orderDetailListStr);

        JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(orderDetailListStr));

        // 解析订单明细
        List<Orderdetail> orderDetailList = jsonArray.toJavaList(Orderdetail.class);
//        List<Orderdetail> orderDetailList = JSONUtils.getList(orderDetailListJson, Orderdetail.class);

        Userinfo userInfo = userinfoService.getUserInfoByRequest(request);
        String userId = userInfo.getId();

        String orderCode = DateUtils.getOrderCode();

        // 处理主信息
        order.setCreateTime(DateUtils.getNow());
        order.setUpdateTime(DateUtils.getNow());
        order.setCreateOp(userId);
        order.setUpdateOp(userId);
        order.setAuditStatus(1);
        order.setOrderCode(orderCode);

        // 处理明细信息
        for (Orderdetail orderdetail : orderDetailList) {
            orderdetail.setOrderCode(orderCode);
            orderDetailService.save(orderdetail);
        }

        boolean result = orderService.save(order);

        return ResponseUtil.ok(result);
    }

    @PostMapping("delete")
    @LogAspect()
    @ApiOperation("删除订单")
    public ResponseDto delete(@RequestBody Map params) {

        Long id = MapUtils.getLong(params, "id");

        boolean result = orderService.removeById(id);

        return ResponseUtil.ok(result);
    }


    @PostMapping("audit")
    @LogAspect()
    @ApiOperation("审核订单")
    public ResponseDto audit(@RequestBody Map params) {

        Long orderId = MapUtils.getLong(params, "orderId");

        int auditStatus = MapUtils.getInteger(params, "auditStatus");

        String auditRemark = MapUtils.getString(params, "auditRemark");
        String orderCode = MapUtils.getString(params, "orderCode");

        Userinfo userInfo = userinfoService.getUserInfoByRequest(request);

        String userId = userInfo.getId();

        // 修改订单审核信息
        Order order = new Order();
        order.setId(orderId);
        order.setAuditOp(userId);
        order.setAuditRemark(auditRemark);
        order.setAuditStatus(auditStatus);
        order.setAuditTime(DateUtils.getNow());

        boolean result = orderService.updateById(order);

        // 审核日志表
        Orderstatuslog orderstatuslog = new Orderstatuslog();
        orderstatuslog.setCreateOp(userId);
        orderstatuslog.setCreateTime(DateUtils.getNow());
        orderstatuslog.setOrderStatus(auditStatus);
        orderstatuslog.setRemark(auditRemark);
        orderstatuslog.setOrderCode(orderCode);
        boolean result2 = orderStatusLogService.save(orderstatuslog);

        boolean finalResult = result && result2;

        return ResponseUtil.ok(finalResult);
    }

    @PostMapping("getActivityList")
    @LogAspect()
    @ApiOperation("获取可以选择的行动计划列表")
    public ResponseDto getActivityList() {
        QueryWrapper<Activity> wrapper = new QueryWrapper<>();

        wrapper.eq("auditStatus",1);

        List<Activity> list = activityService.list(wrapper);

        return ResponseUtil.success(list);

    }


    @PostMapping("getProduct")
    @LogAspect()
    @ApiOperation("获取商品")
    public ResponseDto getProduct(@RequestBody Map params) {


//        String classGuid = MapUtils.getString(params, "classGuid");
        String activityId = MapUtils.getString(params, "activityId");

        String classGuid = activityService.getById(activityId).getClassGuid();

        QueryWrapper<Productitem> productItemWrapper = new QueryWrapper<>();

        productItemWrapper.eq("classGuid",classGuid);
        productItemWrapper.select("itemName");
        String itemName  = productitemService.getOne(productItemWrapper).getItemName();

        QueryWrapper<Product> productQueryWrapper = new QueryWrapper<>();
        productQueryWrapper.eq("productItem",classGuid);
        productQueryWrapper.eq("status",1);

        List<Product> productList = productService.list(productQueryWrapper);


        Map resultMap = new HashMap();
        resultMap.put("itemName",itemName);
        resultMap.put("productList",productList);


        return ResponseUtil.success(productList.size(),resultMap);
    }


    @PostMapping("getStoreAndDistributorList")
    @LogAspect()
    @ApiOperation("获取门店 & 经销商")
    public ResponseDto getStoreAndDistributorList() {
        List<Store> storeList = storeService.list();


        List<Distributor> distributorList = distributorService.list();

        Map data = new HashMap();

        data.put("storeList",storeList);
        data.put("distributorList",distributorList);


        return ResponseUtil.success(2,data);
    }
}
